package com.liao.rabbitmq.service;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MessageService {

    private static final String EXCHANGE_NAME = "RabbitMQ.study";
    private static final String[] QUEUE_NAMES = {"Study_Queue1", "Study_Queue2"};
    private final RabbitTemplate rabbitTemplate;
    //TODO
    //这个不知道为啥注入不了
    private final RabbitAdmin rabbitAdmin;

    @Autowired
    public MessageService(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
//        this.rabbitAdmin = rabbitAdmin;
        this.rabbitAdmin = new RabbitAdmin(rabbitTemplate);
        //创建交换机：FanoutExchange、DirectExchange、HeadersExchange、TopicExchange
        FanoutExchange fanoutExchange = new FanoutExchange(EXCHANGE_NAME, true, true);
        //说明交换机
        this.rabbitAdmin.declareExchange(fanoutExchange);
        for (String queueName : QUEUE_NAMES) {
            //创建队列
            Queue queue = new Queue(queueName, true, false, true);
            //说明队列
            this.rabbitAdmin.declareQueue(queue);
            //创建绑定
            Binding binding = new Binding(queueName, Binding.DestinationType.QUEUE, EXCHANGE_NAME, "", null);
            //声明绑定
            this.rabbitAdmin.declareBinding(binding);
        }
    }

    /**
     * 发送消息
     *
     * @param message message
     */
    public void produce(String message) {
        //因为是广播类型的交换机，所以不需要声明路由键
        rabbitTemplate.convertAndSend(EXCHANGE_NAME, "", message);
    }
}
